package org.ccay.excel.importer.validate.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.ccay.core.util.StringUtil;
import org.ccay.excel.importer.validate.AbstractValidator;
import org.ccay.excel.importer.validate.IStatus;

/**
 * 日期格式校验器
 * 	
 * @author chaowangbang
 * @since Mar 27, 2012
 */
public class DateValidator extends AbstractValidator {
	
	public static final String MESSAGE_KEY = "ccay.excel.validate.date.error";
	/** 日期格式 **/
	private String format;
	
	private SimpleDateFormat dateFormat;
	
	/** 设置日期格式
	 * @author chaowangbang
	 * @since Mar 22, 2012
	 * @param format
	 */
	public void setFormat(String format) {
		this.format = format;
		
		this.dateFormat = new SimpleDateFormat(this.format);
	}

	/* (non-Javadoc)
	 * @see org.ccay.excel.importer.validate.AbstractValidator#doValidate(java.lang.Object)
	 */
	protected IStatus doValidate(Object value) {
		try {
			if(null == value || StringUtil.isNullOrEmpty(value.toString())){
				return IStatus.Ok;
			}
			dateFormat.setLenient(false);
			Date date = null;
			if(Date.class.isAssignableFrom(value.getClass())){
				 date  = (Date) value;
			}else{
				 date = this.dateFormat.parse(value.toString());
			}
			if(1900+date.getYear()>9999){
				return error();
			}
		} catch (ParseException ex) {
			return error();
		}		
		return IStatus.Ok;
	}
}
